﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.Extensions.Primitives;
using System.Globalization;
using System.Threading.Tasks;

namespace Mozhi.Abp.Core.Mvc
{
    public class ArrayQueryStringValueProviderFactory : IValueProviderFactory
    {
        private readonly string _key;

        public ArrayQueryStringValueProviderFactory()
        {
        }

        public ArrayQueryStringValueProviderFactory(string key)
        {
            _key = key;
        }

        public Task CreateValueProviderAsync(ValueProviderFactoryContext context)
        {
            context.ValueProviders.Insert(0, new ArrayQueryStringValueProvider(_key, context.ActionContext.HttpContext.Request.Query));
            return Task.CompletedTask;
        }
    }

    public class ArrayQueryStringValueProvider : QueryStringValueProvider
    {
        private readonly string _key;
        private readonly IQueryCollection _values;

        public ArrayQueryStringValueProvider(IQueryCollection values)
            : this(null, values)
        {
        }

        public ArrayQueryStringValueProvider(string key, IQueryCollection values)
            : base(BindingSource.Query, values, CultureInfo.InvariantCulture)
        {
            _key = key;
            _values = values;
        }

        public override ValueProviderResult GetValue(string key)
        {
            var result = base.GetValue(key + "[]");

            if (_key != null && _key != key)
            {
                return result;
            }
            if (result != ValueProviderResult.None)
            {
                var splitValues = new StringValues(result.Values.ToArray());
                return new ValueProviderResult(splitValues, result.Culture);
            }
            return result;
        }
    }

}
